package cn.wolfcode.wolf2w.interceptor;

import cn.wolfcode.wolf2w.annotation.RequiredLogin;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private IUserInfoRedisService userInfoRedisService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        //如果请求不是动态请求(静态资源),则不是HandlerMethod类型,直接放行
        //如果请求为跨域请求(OPTIONS),则不是HandlerMethod类型,直接放行
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        //handler强转为HandlerMethod类型
        HandlerMethod handlerMethod = (HandlerMethod)handler;

        //拿到请求对象中的token
        String token = request.getHeader("token");
        //根据token查询用户是否存在
        UserInfo userInfo = userInfoRedisService.getUserByToken(token);

        //handlerMethod封装了请求映射方法信息,从里面拿到注解类型,判断是否贴了@RequiredLogin标签,是则进入登录验证方法,否直接放行
        if(handlerMethod.hasMethodAnnotation(RequiredLogin.class)){
            if(userInfo == null){
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
                return false;
            }
        }
        return true;
    }
}
